<?php
// +----------------------------------------------------------------------
// | zhanshop_admin / RequestLog.php [ 2023/4/29 下午10:46 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2023 zhangqiquan All rights reserved.
// +----------------------------------------------------------------------
// | Author: zhangqiquan <768617998@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\middleware;


use zhanshop\App;
use zhanshop\Log;
use zhanshop\server\Request;

class RequestLog
{
    public function handle(Request $request, \Closure $next){
        $response = $next($request);
        $result = $response->getdata();
        if(is_array($result) || is_object($result)){
            $result = json_encode($result, JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE);
        }
        $rep = [
            'time' => date('Y-m-d H:i:s', $request->time()),
            'url' => $request->server('request_uri'),
            'ip' => $request->realIp(),
            'agent' => $request->server('user-agent'),
            'uid' => $request->getData('user.user_id', 0),
            'code' => 0,
            'msg' => "OK",
            'request' => [
                'get' => $request->get(),
                'post' => $request->post(),
                'file' => $request->files(),
                'raw' => mb_substr($request->rawRequest()->getContent(), 0, 4000)
            ],
            'response' => mb_substr(strval($result), 0, 4000),
            'runtime' => microtime(true) - $request->time(true),
        ];
        App::log()->push(json_encode($rep, JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE), Log::NOTICE, "REQUEST");
        return $response;
    }
}